const db = uniCloud.database();
// console.log('unreadCounts',unreadCounts);
export default new class {
	constructor(){
		if(typeof getApp != 'undefined'){
			this.init()
		}
	}
	unreadCounts = false
	isInIt = false
	init(){
		console.log('isInIt')
		if(this.isInIt){
			// return //console.log('isInIt')
		}
		
		if (!getApp().globalData.uniNotificationCenter) {
			getApp().globalData.uniNotificationCenter = {
				unreadCounts: false,
				data: []
			}
		}
		let {
			unreadCounts
		} = getApp().globalData.uniNotificationCenter;
		
		this.getUnreadCount = (type_code)=>{
			let n = 0
			for (let key in unreadCounts) {
				let item = unreadCounts[key]
				if(!type_code || type_code == key ){
					n += item
				}
			}
			return n
		}
		Object.defineProperty(this, 'unreadCounts', {
			get() {
				return unreadCounts
			},
			set: (value) => {
				console.log('unreadCounts set',this.taskFns);
				unreadCounts = value
				this.taskFns.forEach(({callback,type_code}) =>{
					callback(this.getUnreadCount(type_code))
				})
			}
		})
		// 刷新未读消息数
		uni.onPushMessage(res=>{
			if(res.data.payload.type == 'uni-notification-center'){
				this.refreshUnreadCount()
			}
		})
		this.isInIt = true
	}
	taskFns = []
	async bindUnreadCount(callback,type_code) {
		if(!this.isInIt){
			this.init()
		}
		
		// console.log('bindUnreadCountbindUnreadCount');
		
		this.taskFns.push({callback,type_code})
		// 判断是否已经从服务器中拉取过数据，值=false表示未拉取
		if (this.unreadCounts === false) {
			await this.refreshUnreadCount()
		} else {
			// 拉取过就直接返回值
			callback(this.getUnreadCount(type_code))
		}
	}
	async refreshUnreadCount() {
		if(this.refreshUnreadCount.lock){
			return //console.log('is lock')
		}
		this.refreshUnreadCount.lock = true
		// console.log('refreshUnreadCount');
		
		// 统计未读的 "私发"记录
		let res = await db.collection('uni-notification-center')
			.where(`"is_read" == ${false} && "user_id" == $cloudEnv_uid`)
			.groupBy("type_code")
			.groupField("sum(1) as total")
			.orderBy("create_time desc")
			.get()
		// 再根据 type_code 分类 得到数量
		let unreadCounts =  res.result.data.reduce((sum,current)=>{
			sum[current.type_code] = current.total
			return sum
		},{})
		console.log('unreadCounts',unreadCounts);
		
		
		// 统计未读的 "公告"记录（只统计最新的500条）
		/*
			1. 查出所有公告数据
			2. 判断哪些未读
		*/
		let uncTemp = await db.collection('uni-notification-center')
								.where(`"to_all" == ${true}`) // 发给所有人
								.getTemp()
		let uncReadLogTemp = await db.collection('uni-notification-read-log')
								.where('"user_id" == $cloudEnv_uid')
								.getTemp()
		res = await db.collection(uncTemp,uncReadLogTemp)
						// .orderBy("create_time desc")
						// .groupBy("type_code")
						// .groupField("sum(1) as total")
						.get()
		console.log('res-resresres-----------',res.result.data);
		
		res.result.data.forEach(({type_code,_id})=>{
			let [log] = _id['uni-notification-read-log']
			if(log){
				// console.log('已经读取的公告消息_id:'+log.notification_id)
			}else{
				if(unreadCounts[type_code]){
					unreadCounts[type_code] ++
				}else{
					unreadCounts[type_code] = 1
				}
			}
		})
		
		this.unreadCounts = unreadCounts
		this.refreshUnreadCount.lock = false
		// console.log('this.unreadCounts',this.unreadCounts);
	}
}
